package org.layuiframework.stereotype.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.layuiframework.stereotype.vo.ResultVo;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 访问接口没有权限时，自定义返回结果
 */
@Component
@ConditionalOnMissingBean(AccessDeniedHandler.class)
public class RestfulAccessDeniedHandler implements AccessDeniedHandler {

    /**
     * Handles an access denied failure.
     *
     * @param request               that resulted in an <code>AccessDeniedException</code>
     * @param response              so that the user agent can be advised of the failure
     * @param accessDeniedException that caused the invocation
     * @throws IOException      in the event of an IOException
     * @throws ServletException in the event of a ServletException
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.setStatus(403);
        PrintWriter out = response.getWriter();
        ResultVo responseEntity = new ResultVo((Object) null);
        responseEntity.setCode(403);
        responseEntity.setMsg("没有访问权限");
        out.write(new ObjectMapper().writeValueAsString(responseEntity));
        out.flush();
        out.close();
    }
}
